<template>
  <div class="meter-pie-container" ref="echarts_instance"></div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Component, Ref, Watch, Prop, Emit } from 'vue-property-decorator'
import * as echarts from 'echarts'
import { Getter } from 'vuex-class'
import { Dictionary } from 'vue-router/types/router'
type EchartsOptions = echarts.EChartsOption
@Component
class MeterPie extends Vue {
  @Getter('theme') theme!: 'dark' | 'light'
  @Ref() echarts_instance!: HTMLElement
  @Prop({ required: true }) pieData!: Dictionary<number>
  @Prop({ default: () => [] }) selected!: string[]
  myChart: echarts.ECharts | null = null
  get FormatedPieData() {
    return Object.keys(this.pieData).map(key => ({ name: key, value: this.pieData[key] }))
  }
  @Watch('theme')
  theme_handler() {
    this.initEcharts()
  }
  @Watch('pieData')
  data_handler() {
    this.initEcharts()
  }
  mounted() {
    this.myChart = echarts.init(this.echarts_instance)
    this.myChart.on('legendselectchanged', params => {
      this.onSelectedChange(params)
    })
    this.initEcharts()
  }
  initEcharts() {
    if (!this.myChart) return
    const echartsOption: EchartsOptions = {
      // color: ['#09B1EC', '#28DCD0', '#FFE37E', '#FFC3CE'],
      tooltip: {
        trigger: 'item',
        textStyle: {
          align: 'left',
          fontSize: 12
        }
      },
      legend: {
        top: 'middle',
        left: '5%',
        orient: 'vertical',
        textStyle: {
          color: '#ffffff'
        }
      },
      series: [
        {
          type: 'pie',
          radius: [40, 80],
          center: ['65%', '50%'],
          label: {
            show: false
          },
          labelLine: {
            length: 5,
            length2: 5
          },
          data: this.FormatedPieData
        }
      ],
      textStyle: {
        color: '#ffffff'
      }
    }
    this.myChart.setOption(echartsOption)
    this.myChart.resize()
    window.addEventListener('resize', () => {
      if (!this.myChart) return
      this.myChart.resize()
    })
  }
  @Emit()
  onSelectedChange(params: unknown) {
    const { selected } = params as { selected: Dictionary<boolean> }
    const result: string[] = []
    for (const proper in selected) {
      if (selected[proper]) result.push(proper)
    }
    return result
  }
}
export default MeterPie
</script>

<style lang="less" scoped>
.meter-pie-container {
  width: 100%;
  height: 100%;
}
</style>
